//
//  ViewController.m
//  Picture
//
//  Created by 孙玉琢 on 16/11/21.
//  Copyright © 2016年 孙玉琢. All rights reserved.
//

#import "ViewController.h"
#import "ZTStickerView.h"
#import "FinishViewController.h"
#import "EditImageController.h"
#import "ColorView.h"
#import "UIColor+Hex.h"
#import "StickersViewController.h"
#import "ImageEditView.h"
#import "MPOpenReplyViewController.h"
#import "UIImage+RTTint.h"
// 屏幕高度
#define HEIGHT [UIScreen mainScreen].bounds.size.height
// 屏幕宽度
#define WIDTH [UIScreen mainScreen].bounds.size.width
//颜色string
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


@interface ViewController ()<ZTStickerViewDelegate,UITableViewDataSource, UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ColorViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,ImageEditViewDelegate>
@property (nonatomic,strong)UITableView *hTable;
@property(nonatomic,strong)UIImageView *originImageView;
@property (nonatomic,strong) NSMutableArray *stickerArray;
@property (nonatomic,assign) NSInteger newStickerID ;

@property (nonatomic, strong)UIView * backView;
@property (nonatomic, strong)UIImage * image;

@property (nonatomic, strong)UIImageView * windowImageView;//按钮

@property (nonatomic, strong)UIView * chooseView;

@property (nonatomic, strong)UIView * backColorView;//背景颜色view

@property (nonatomic)NSInteger currentBeijingID;//背景viewID
@property (nonatomic)NSInteger backImageTAG;//被挡在下面的image的TAG
@property (nonatomic, strong)UIColor * currentBeijingColor;//当前背景view颜色

@property (nonatomic, strong)ZTStickerView * currentStickerView;//当前编辑的stickerView

@property (nonatomic, strong)ColorView * colorView;//选择颜色的view
@property (nonatomic, strong)ImageEditView * imageEditView;//编辑形状view

@property (nonatomic, strong)UIView * tapView;//添加手势view

@property (nonatomic, strong)ZTStickerView * sameStickerView;//透明与下层stickerView frame一样的view
@property (nonatomic, assign) BOOL whoCare; //Yes是拍照 No是相册选择 用于判断滤镜页面的左上角UI

@property (nonatomic, strong)UIImage *screenImage; //截屏image，用于设置栈view背景
@property (nonatomic, strong)UIImage *originalImage; //保存无滤镜效果的图片
@property (nonatomic, strong) UICollectionView * collect;
@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, strong) NSArray *nameArray;
@property (nonatomic, strong) NSArray *stickersArray; //贴纸数组
@property (nonatomic, strong) NSArray *borderArray;   //边框数组
@property (nonatomic, strong) NSArray *materialArray; //表情数组
@property (nonatomic, strong) NSArray *grainArray;    //纹路数组
@property (nonatomic, strong) NSArray *linellaeArray; //线条数组
@property (nonatomic, strong) NSArray *shapeArray;    //形状数组

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    [self InitializeArray];
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake((WIDTH -  (1181 * (HEIGHT - 64 -  200)) / 1748) / 2 - 20, 20, (1181 * (HEIGHT - 64 - 200)) / 1748 + 40, HEIGHT - 64 - 50)];
    self.backView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:self.backView];
    
    self.originImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, (1181 * (HEIGHT - 200)) / 1748, HEIGHT - 50 - 64)];
    self.originImageView.image = [UIImage imageNamed:@"ke1"];
    
    self.originImageView.userInteractionEnabled = YES;
    self.originImageView.clipsToBounds = YES;
    [self.backView addSubview:self.originImageView];
    
    UIButton * doneBtn = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH - 50, 20, 50, 40)];
    [doneBtn setTitle:@"完成" forState:UIControlStateNormal];
    [doneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [doneBtn addTarget:self action:@selector(pasterDone) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:doneBtn];
    
    self.stickerArray = [@[]mutableCopy];
    self.windowImageView = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH -  (1181 * (HEIGHT - 64 -  200)) / 1748) / 2 - 20, 20, (1181 * (HEIGHT - 64 - 200)) / 1748 + 40, HEIGHT - 64 - 50)];
    self.windowImageView.image = [UIImage imageNamed:@"moble_bt"];
    [self.view addSubview:self.windowImageView];
    [self horizontalTableview];
    [self setChooseView];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];
    if (self.chooseView) {
        self.chooseView.hidden =YES;
    }
}
- (void)tap:(UITapGestureRecognizer *)tapGesture
{
    if (self.colorView) {
        self.colorView.hidden = YES;
        [self.tapView removeFromSuperview];
    }
    if (self.imageEditView) {
        self.imageEditView.hidden = YES;
        [self.tapView removeFromSuperview];
    }
    if (self.tapView) {
        [self.tapView removeFromSuperview];
    }
}
//选背景颜色View
- (void)setColorview:(float)alpha
{
    //选颜色
    self.colorView = [[NSBundle mainBundle] loadNibNamed:@"ColorView" owner:self options:nil].lastObject;
    self.colorView.frame = CGRectMake(0, HEIGHT - 150, WIDTH, 150);
    self.colorView.delegate = self;
    self.colorView.slider.value = alpha;
    [self.view addSubview:self.colorView];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)] ;
    self.tapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 150)];
    [self.tapView addGestureRecognizer:tapGesture];
    [self.view addSubview:self.tapView];
}
-(void)setChooseView{
//实例化chooseView
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 100)];
    headerView.backgroundColor = [UIColor clearColor];
    
    UILabel *textLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, WIDTH, 40)];
    textLable.textColor = [UIColor whiteColor];
    textLable.text = @"添加新图层";
    [textLable setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    textLable.textAlignment = NSTextAlignmentCenter;
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-60, 10, 50, 50)];
    [button setImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    self.chooseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.chooseView.hidden = YES;
    self.chooseView.backgroundColor = [UIColor blackColor];
    self.chooseView.alpha =0.8;
    
    _imagePickerVC = [[UIImagePickerController alloc]init];
    _imagePickerVC.delegate=self;
    //实例化headerview
    //创建一个layout布局类
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //设置布局方向为垂直流布局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置每个item的大小为100*100
    layout.itemSize = CGSizeMake(100, 100);
    //创建collectionView 通过一个布局策略layout来创建
    self.collect = [[UICollectionView alloc]initWithFrame:CGRectMake((WIDTH-320)/2, 100, 320,HEIGHT-120) collectionViewLayout:layout];
    self.collect.backgroundColor = [UIColor clearColor];
    //代理设置
    self.collect.delegate=self;
    self.collect.dataSource=self;

//注册item类型 这里使用系统的类型
    [self.collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    [self.view addSubview:self.chooseView];
    [self.chooseView addSubview:self.collect];
    [self.chooseView addSubview:headerView];
    [headerView addSubview:textLable];
    [headerView addSubview:button];

}
- (void)setimageEditView:(ZTStickerView *)stickerView imageEditViewType:(int)imageEditViewType
{
    self.imageEditView = [[[NSBundle mainBundle] loadNibNamed:@"ImageEditView" owner:self options:nil] lastObject];
    self.imageEditView.stickerViewID = stickerView.stickerID;
    self.imageEditView.type = imageEditViewType;
    if (imageEditViewType == 2) {//形状
        
        self.imageEditView.forthBtn.hidden = YES;
        [self.imageEditView.thiBtn setImage:[UIImage imageNamed:@"3-编辑-图片_32"] forState:UIControlStateNormal];
        [self.imageEditView.thiBtn setImage:[UIImage imageNamed:@"3-编辑-图片_32"] forState:UIControlStateHighlighted];
        
    }else if (imageEditViewType == 3){//文字
        [self.imageEditView.thiBtn setImage:[UIImage imageNamed:@"3-编辑-图片_32"] forState:UIControlStateNormal];
        [self.imageEditView.thiBtn setImage:[UIImage imageNamed:@"3-编辑-图片_32"] forState:UIControlStateHighlighted];
        [self.imageEditView.forthBtn setImage:nil forState:UIControlStateNormal];
        [self.imageEditView.forthBtn setImage:nil forState:UIControlStateHighlighted];
        [self.imageEditView.forthBtn setTitle:@"A" forState:UIControlStateNormal];
        [self.imageEditView.forthBtn setTitle:@"A" forState:UIControlStateHighlighted];
        self.imageEditView.forthBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
        self.imageEditView.forthBtn.titleLabel.textColor = [UIColor blackColor];
    }
    self.imageEditView.frame = CGRectMake(0, HEIGHT - 150, WIDTH, 150);
    self.imageEditView.delegate = self;
    self.imageEditView.slider.value = stickerView.frame.size.width/750.0;
    self.imageEditView.alphaValue.value = stickerView.alpha;
    [self.view addSubview:self.imageEditView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)] ;
    self.tapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 50)];
    [self.tapView addGestureRecognizer:tapGesture];
    [self.view addSubview:self.tapView];
}
//ImageEditView   移动
- (void)changeCenter:(NSInteger)tag stickerViewID:(NSInteger)stickerViewID
{
    ZTStickerView * stickerView = [self.view viewWithTag:9000 + stickerViewID];
    if (tag == 3001) {//左移
        stickerView.center = CGPointMake(stickerView.center.x - 1, stickerView.center.y);
    }
    if (tag == 3002) {//右移
        stickerView.center = CGPointMake(stickerView.center.x + 1, stickerView.center.y);
    }
    if (tag == 3003) {//上移
        stickerView.center = CGPointMake(stickerView.center.x, stickerView.center.y - 1);
    }
    if (tag == 3004) {//下移
        stickerView.center = CGPointMake(stickerView.center.x, stickerView.center.y + 1);
    }
}
//ImageEditView放大缩小
- (void)changeSliderValue:(float)value stickerViewID:(NSInteger)stickerViewID
{
    
    ZTStickerView * stickerView = [self.view viewWithTag:9000 + stickerViewID];
    stickerView.transform = CGAffineTransformMakeRotation(stickerView.angle);
    stickerView.transform = CGAffineTransformScale(stickerView.transform, value * 5, value * 5);
    
}
//imageEditView  按钮点击改变height
- (void)changeSelfHeight:(NSInteger)tag stickerViewID:(NSInteger)stickerViewID imageEditType:(int)imageEditType
{
    ZTStickerView * stickerView = [self.view viewWithTag:9000 + stickerViewID];
    
    if (tag == 4001) {//缩放
        if (imageEditType == 1 || imageEditType == 2 || imageEditType == 3) {
            self.tapView.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 150);
            self.imageEditView.slider.value = stickerView.frame.size.width/750.0;
        }
        
    }else if (tag == 4002){//变换角度
        if (imageEditType == 1 || imageEditType == 2 || imageEditType == 3) {
            self.tapView.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 100);
            if (180/M_PI * stickerView.angle  == -0) {
                self.imageEditView.angleValue.text = @"0˚";
            }else
            {
                self.imageEditView.angleValue.text = [NSString stringWithFormat:@"%.0f˚",180/M_PI * stickerView.angle];
            }
        }
        
    }else if (tag == 4003){//透明度变化
        if (imageEditType == 1) {
            self.tapView.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 100);
            
        }else if (imageEditType == 2 || imageEditType == 3){
            self.tapView.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 150);

        }
        
        self.imageEditView.alphaValue.value = stickerView.alpha;

    }else if (tag == 4004){
        if (imageEditType == 1) {//滤镜
            [self editFilter:stickerView];
            self.imageEditView.hidden = YES;
            [self.tapView removeFromSuperview];
        }else if (imageEditType == 3){//修改字内容
            [self screenShot];
            //弹出输入框输入框
            MPOpenReplyViewController *vc = [[MPOpenReplyViewController alloc]init];
            vc.bgImg =self.screenImage;
            vc.text = ^(NSString *str){
                [self getFitSize:str stickerView:stickerView];
            };
            [self presentViewController:vc animated:NO completion:nil];
        }
        
    }
}
//imageEditView改变angle
- (void)changeAngle:(NSInteger)tag stickerViewID:(NSInteger)stickerViewID
{
    float angle = M_PI/180 ;
    
    ZTStickerView * stickerView = [self.view viewWithTag:9000 + stickerViewID];
    if (tag == 7001) {//逆时针
        int imageEditAngleValue = [self.imageEditView.angleValue.text intValue] - 1;
        self.imageEditView.angleValue.text = [NSString stringWithFormat:@"%d˚",imageEditAngleValue];
        stickerView.angle = stickerView.angle - angle;
        stickerView.transform = CGAffineTransformMakeRotation(stickerView.angle);
        [stickerView setNeedsDisplay];
        
        if ([self.imageEditView.angleValue.text intValue] <= 0) {
            int imageEditAngleValue = 360 + [self.imageEditView.angleValue.text intValue];
            self.imageEditView.angleValue.text = [NSString stringWithFormat:@"%d˚",imageEditAngleValue];
        }
        
    }else if (tag == 7002){//顺时针
        
        int imageEditAngleValue = [self.imageEditView.angleValue.text intValue] + 1;
        self.imageEditView.angleValue.text = [NSString stringWithFormat:@"%d˚",imageEditAngleValue];
        stickerView.angle = stickerView.angle + angle;
        stickerView.transform = CGAffineTransformMakeRotation(stickerView.angle);
        if ([self.imageEditView.angleValue.text intValue] >= 360) {
            int imageEditAngleValue = [self.imageEditView.angleValue.text intValue] - 360;
            self.imageEditView.angleValue.text = [NSString stringWithFormat:@"%d˚",imageEditAngleValue];
        }
        
    }
    
}
//imageEditView改变Alpha
- (void)changeAlpha:(float)value stickerViewID:(NSInteger)stickerViewID
{
    ZTStickerView * stickerView = [self.view viewWithTag:9000 + stickerViewID];
    stickerView.transform = CGAffineTransformMakeRotation(stickerView.angle);
    stickerView.alpha = value;
}
//imageEditView删除图层
- (void)delStickerView:(NSInteger)stickerViewID
{
    [self removeSticker:stickerViewID];
}
//imageEditView改变贴纸颜色
- (void)changeColor:(NSString *)colorString stickerViewID:(NSInteger)stickerViewID
{
    ZTStickerView * stickerView = [self.view viewWithTag:9000 + stickerViewID];
    self.currentStickerView = stickerView;
    
    UIImage *tinted = [stickerView.stickerImg rt_tintedImageWithColor:[UIColor hexStringToColor:colorString]];

    stickerView.stickerImg = tinted;
    
    [_hTable reloadData];
    
}

//开线程实例化图片数组
-(void)InitializeArray{
    NSLog(@"开启多线程");
    dispatch_queue_t itemImageArray = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(itemImageArray, ^{
        NSLog(@"itemImageArray...sync...%@",[NSThread currentThread]);
        //图片和名称数组
        self.imageArray = @[@"照相机",@"相册",@"素材库",@"背景色",@"形状",@"贴纸",@"图形文字",@"文字",@"线条",@"纹路",@"边框",@"彩色贴纸"];
        self.nameArray =@[@"照相机",@"相册",@"素材库",@"背景色",@"形状",@"贴纸",@"图形文字",@"文字",@"线条",@"纹路",@"边框",@"彩色贴纸"];
    
        self.stickersArray =@[@"t01",@"t02",@"t03",@"t04",@"t05",@"t06",@"t07",@"t08",@"t09",@"t10",@"t11",@"t12",@"t13"];
        self.borderArray =@[@"bk01",@"bk02",@"bk03",@"bk04",@"bk05",@"bk06",@"bk07",@"bk08"];
        self.materialArray =@[@"b_01",@"b_02",@"b_03",@"b_04",@"b_05",@"b_06",@"b_07",@"b_08",@"b_09",@"b_10",@"b_11",@"b_12",@"b_13",@"b_14",@"b_15",@"b_16",@"b_17",@"b_18",@"b_19",@"b_20",@"b_21",@"b_22",@"b_23",@"b_24",@"b_25",@"b_26"];
        self.grainArray =@[@"底纹_01",@"底纹_02",@"底纹_03",@"底纹_04",@"底纹_05",@"底纹_06"];
        self.linellaeArray =@[@"tw_01",@"tw_02",@"tw_03",@"tw_04",@"tw_05",@"tw_06",@"tw_07",@"tw_08",@"tw_09"];
        self.shapeArray =@[@"x01",@"x02",@"x03",@"x04",@"x05",@"x06",@"x07",@"x08",@"x09",@"x10",@"x11",@"x12"];
    });
    NSLog(@"结束多线程");
}
//返回分区个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
//返回每个分区的item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imageArray.count;
}
//返回每个item
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(30, 15, 40, 40)];
    image.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",self.imageArray[indexPath.row]]];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, 100, 40)];
    lable.text = self.nameArray[indexPath.row];
    lable.textColor = [UIColor whiteColor];
    [lable setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14]];
    lable.textAlignment =NSTextAlignmentCenter;
    
    UILabel *roundLable = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, 60, 60)];
    roundLable.layer.borderColor =[[UIColor whiteColor] CGColor];
    roundLable.layer.borderWidth = 2;
    roundLable.layer.cornerRadius = roundLable.frame.size.width/2;
    roundLable.clipsToBounds = YES;

    [cell.contentView addSubview:image];
    [cell.contentView addSubview:lable];
    [cell.contentView addSubview:roundLable];
    return cell;
}

#pragma mark -UICollectionViewDelegate
//UICollectionView被选中的时候调用
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%zd",indexPath.item);
    self.chooseView.hidden =YES;
    switch (indexPath.item) {
        case 0:
        {
            NSLog(@"照相机");
            [self clickZhaoXiangJi];
        }
            break;
        case 1:
        {
            NSLog(@"相册");
            [self clickXiangPian];
        }
            break;
        case 2:
        {
            NSLog(@"素材库");
        }
            break;
        case 3:
        {
            NSLog(@"背景色");
            [self clickBeiJing];
        }
            break;
        case 4:
        {
            NSLog(@"形状");
            [self clickItemImage:self.shapeArray title:@"形状" type:4];
        }
            break;
        case 5:
        {
            NSLog(@"贴纸");
            [self clickItemImage:self.stickersArray title:@"贴纸" type:5];
        }
            break;
        case 6:
        {
            NSLog(@"图形文字");
            
        }
            break;
        case 7:
        {
            NSLog(@"文字");
            [self clickCharacter];//type 10
        }
            break;
        case 8:
        {
            NSLog(@"线条");
            [self clickItemImage:self.linellaeArray title:@"线条" type:6];
        }
            break;
        case 9:
        {
            NSLog(@"纹路");
            [self clickItemImage:self.grainArray title:@"纹路" type:7];
        }
            break;
        case 10:
        {
            NSLog(@"边框");
            [self clickItemImage:self.borderArray title:@"边框" type:8];
        }
            break;
        case 11:
        {
            NSLog(@"彩色贴纸");
            [self clickItemImage:self.materialArray title:@"彩色贴纸" type:9];

            
        }
            break;
        default:
            break;
    }
}
-(void)back{
    
    self.chooseView.hidden = YES;
}
//照相机
- (void)clickZhaoXiangJi
{
    [_imagePickerVC setSourceType:UIImagePickerControllerSourceTypeCamera];
    [self presentViewController:self.imagePickerVC animated:YES completion:nil];
    self.whoCare = YES;

}
//相册
- (void)clickXiangPian
{
     [_imagePickerVC setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
     [self presentViewController:self.imagePickerVC animated:YES completion:nil];
    self.whoCare = NO;
}
//背景色
- (void)clickBeiJing
{
    if (self.currentBeijingColor == nil) {
        self.currentBeijingColor = [UIColor blackColor];
    }
    [self addBeiJingSticker:0 currentColor:self.currentBeijingColor];
    self.chooseView.hidden = YES;
}

-(void)clickItemImage:(NSArray*)nameArray title:(NSString*)title type:(int)type{
    
    StickersViewController *vc = [[StickersViewController alloc]init];
    vc.imageArray = nameArray;
    vc.itemTitle =title;
    vc.backImage =self.screenImage;
    [self presentViewController:vc animated:YES completion:nil];
    __weak typeof(self) weakSelf = self;
    vc.imageBlock =^(NSString *str){
        UIImage *image =[UIImage imageNamed:str];
        [weakSelf addSticker:image type:type];
    };
}

//文字
-(void)clickCharacter{
    MPOpenReplyViewController *vc = [[MPOpenReplyViewController alloc]init];
    vc.bgImg =self.screenImage;
    vc.text = ^(NSString *str){
        [self getFitSize:str stickerView:nil];
    };
    [self presentViewController:vc animated:NO completion:nil];
}
//计算返回字体在30号font下的宽高
-(void)getFitSize:(NSString *)str stickerView:(ZTStickerView *)stickerView{
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    lable.text = str;
    lable.font = [UIFont systemFontOfSize:30];
    [lable sizeToFit];
    CGSize size =CGSizeMake(lable.frame.size.width, lable.frame.size.height);
    
//    if (!stickerView) {
//        [self characterView:str characterSize:size stickerView:stickerView];
//    }else
//    {
//        [self removeSticker:stickerView.stickerID];

    [self characterView:str characterSize:size stickerView:stickerView];
//    }
    
}
//返回文字+宽高生成目标View
-(void)characterView:(NSString*)text characterSize:(CGSize)size stickerView:(ZTStickerView *)stickerView{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    view.backgroundColor = [UIColor clearColor];
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    lable.text = text;
    lable.textColor = [UIColor blackColor];
    lable.font = [UIFont systemFontOfSize:30];
    [view addSubview:lable];
    if (!stickerView) {
        [self addSticker:[self getImageFromView:view] type:10];//文字
    }else
    {
        for (int i=0; i<_stickerArray.count; i++) {
            ZTStickerView *stickerView1 = _stickerArray[i];
            if (stickerView.stickerID == stickerView1.stickerID) {
                
                stickerView.stickerImg = [self getImageFromView:view];
                [self.stickerArray replaceObjectAtIndex:i withObject:stickerView];

            }
        }
    }
    [_hTable reloadData];
}
//View转Image
-(UIImage *)getImageFromView:(UIView *)theView
{
    CGSize s = theView.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark-
#pragma mark AlertView代理
-(void)goEditImageController{
    self.editImageController = [[EditImageController alloc] init];
    self.editImageController.image = self.image;
    [self presentViewController:self.editImageController animated:YES completion:nil];
    self.editImageController.iCare = NO;
    if (self.whoCare == YES) {
        self.editImageController.iCare = YES;
    }
    __weak typeof(self) weakSelf = self;
    self.editImageController.returnUseImageBlock = ^(UIImage *iconImage,UIImage *originalImage){
        [weakSelf addSticker:iconImage type:1];
        weakSelf.originalImage =originalImage;
    };
}
//图片编辑滤镜进入该方法
-(void)editFilter:(ZTStickerView *)stickerView{
    self.editImageController = [[EditImageController alloc] init];
    if (self.originalImage) {
        self.editImageController.image = self.image;
    }
     self.editImageController.iCare = YES;
     [self presentViewController:self.editImageController animated:YES completion:nil];
    __weak typeof(self) weakSelf = self;
    self.editImageController.returnUseImageBlock = ^(UIImage *iconImage,UIImage *originalImage){        weakSelf.originalImage =originalImage;
        for (int i=0; i<_stickerArray.count; i++) {
            ZTStickerView *stickerView1 = weakSelf.stickerArray[i];
            if (stickerView.stickerID == stickerView1.stickerID) {
                stickerView.stickerImg = iconImage;
                [weakSelf.stickerArray replaceObjectAtIndex:i withObject:stickerView];
                [weakSelf.hTable reloadData];
            }
        }
    };
    

}
/*!
 *  @author 陈迪, 16-11-24
 *
 *  压缩图片至目标尺寸
 *
 *  @param sourceImage 源图片
 *  @param targetWidth 图片最终尺寸的宽
 *
 *  @return 返回按照源图片的宽、高比例压缩至目标宽、高的图片
 */
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    CGFloat targetHeight = (targetWidth / width) * height;
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}
#pragma -mark ImagePickDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
   __block UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:NO completion:nil];
//获取image进行判断，若width超过1300，则等比压缩宽度为1242【苹果P系列截屏image标准宽度】,否则不作处理。
    if (image.size.width>1300) {
        self.image = [self compressImage:image toTargetWidth:1242];
    }else{
        self.image =image;
    }
        self.chooseView.hidden = YES;
        [self goEditImageController];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//添加背景颜色
- (void)addBeiJingSticker:(NSInteger)stickerID currentColor:(UIColor *)currentColor
{
    ZTStickerView *stickerView;
    if (stickerID == 0) {
        UIImage * colorImg = [self imageWithColor:currentColor size:self.backView.frame.size];
        stickerView = [[ZTStickerView alloc] initWithBgView:self.originImageView StickerID:self.newStickerID Img:colorImg];
        stickerView.frame = self.originImageView.frame;
        stickerView.type = 2;
        self.currentBeijingID = stickerView.stickerID;
        stickerView.delegate = self ;
        stickerView.isOnEdit = NO;
        [_stickerArray addObject:stickerView] ;
        [self makeStickerBecomeFirstRespond:stickerView.stickerID type:2];//2代表背景图片
    }else
    {
        stickerView = [self.view viewWithTag:9000+stickerID];
        self.currentStickerView = stickerView;
        UIImage * colorImg = [self imageWithColor:currentColor size:self.backView.frame.size];
        stickerView.stickerImg = colorImg;

    }
    
    [_hTable reloadData];
}
/*
 *生成一张纯色的图片
 */
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

/**
 *截图功能
 */
-(void)screenShot{
    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.screenImage =image;
}
//关闭按钮
- (void)clickClose
{
    self.chooseView.hidden = YES;
}

//创建横着的tableview
- (void)horizontalTableview
{
    UIView *htableView = [[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT - 100, WIDTH, 100)];
    htableView.backgroundColor = [UIColor colorWithRed:37.0 / 255.0 green:37.0 / 255.0 blue:37.0 / 255.0 alpha:1];
    
    [self.view addSubview:htableView];
    
    _hTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 80, 70, WIDTH)];
    _hTable.delegate = self;
    _hTable.dataSource = self;
    _hTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    _hTable.showsVerticalScrollIndicator = NO;
    _hTable.tableFooterView = [[UIView alloc]init];
    _hTable.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 70, 10)];
    [_hTable.layer setAnchorPoint:CGPointMake(0, 0)];
    _hTable.transform = CGAffineTransformMakeRotation(M_PI/-2);
    _hTable.frame = CGRectMake(0, 80, WIDTH, 70);
    _hTable.rowHeight = 58;
    _hTable.backgroundColor = [UIColor clearColor];
    
    [htableView addSubview:_hTable];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.stickerArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }
    
    if (indexPath.row == 0) {
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 70, 60)];
        label.text = @"+";
        label.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:label];
         return cell;
    }else
    {
        cell.contentView.transform = CGAffineTransformMakeRotation(M_PI/2);
        cell.backgroundColor = [UIColor clearColor];
        
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 55, 64)];
        [image setContentMode:UIViewContentModeScaleAspectFit];
        ZTStickerView * stickerView = self.stickerArray[indexPath.row - 1];
        image.image = stickerView.imgContentView.image;
        if (self.currentStickerView == stickerView) {
            image.layer.borderColor = [UIColor greenColor].CGColor;
            image.layer.borderWidth = 1.0;
//            if (stickerView.type == 1) {//图片
//                [self setSameStickerView:stickerView];
//            }
        }else
        {
            image.layer.borderColor = [UIColor clearColor].CGColor;
            image.layer.borderWidth = 0.0;
        }
        [cell.contentView addSubview:image];
        return cell;
    }
    
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.sameStickerView removeFromSuperview];
    if (indexPath.row == 0) {
        [self screenShot];
        self.chooseView.hidden = NO;
        
    }else
    {
        BOOL haveColorView = NO;
        for (ZTStickerView * stickerView in self.stickerArray) {
            if (stickerView.type == 2) {
                haveColorView = YES;
                break;
            }
        }
        ZTStickerView * stickerView = self.stickerArray[indexPath.row - 1];
        if (stickerView.type == 1 || stickerView.type == 8 || stickerView.type == 9) {//点击图片
//            [self setimageEditView:stickerView];
            self.colorView.hidden = YES;
            if (haveColorView == NO) {
                [self tapGesture:stickerView.stickerID clickType:1];
            }else
            {
                //生成一个透明的   stickerView.frame的透明View
                [self drawSameStickerView:stickerView clickType:1];
            }
            

        }else if (stickerView.type == 2){//背景颜色
            self.imageEditView.hidden = YES;
            [self setColorview:stickerView.alpha];
            self.currentStickerView = stickerView;
            self.colorView.stickerViewID = stickerView.stickerID;
        }else if (stickerView.type == 4 || stickerView.type == 5 || stickerView.type == 6 || stickerView.type == 7){//形状
            
//            [self tapGesture:stickerView.stickerID clickType:1];
            if (haveColorView == NO) {
                [self setimageEditView:stickerView imageEditViewType:2];
                self.currentStickerView = stickerView;
                self.imageEditView.stickerViewID = stickerView.stickerID;
            }else
            {
                //生成一个透明的   stickerView.frame的透明View
                [self drawSameStickerView:stickerView clickType:1];
            }
            
            
        }else if (stickerView.type == 10){//文字
            if (haveColorView == NO) {
                [self setimageEditView:stickerView imageEditViewType:3];
                self.currentStickerView = stickerView;
                self.imageEditView.stickerViewID = stickerView.stickerID;
            }else
            {
                //生成一个透明的   stickerView.frame的透明View
                [self drawSameStickerView:stickerView clickType:1];

            }
            
            
//            if (haveColorView == NO) {
//                [self tapGesture:stickerView.stickerID clickType:1];
//            }else
//            {
//                //生成一个透明的   stickerView.frame的透明View
//                [self drawSameStickerView:stickerView clickType:1];
//            }

            
        }
//        NSLog(@"%ld",(long)indexPath.row);

    }
    
    [_hTable reloadData];
}
- (void)drawSameStickerView:(ZTStickerView *)view clickType:(int)clickType
{
//    self.sameStickerView = [[ZTStickerView alloc] initWithBgView:self.originImageView  StickerID:view.stickerID Img:nil];
//    self.sameStickerView.backgroundColor = [UIColor blueColor];
////    self.sameStickerView.alpha = 0.0;
//    self.sameStickerView.isOnEdit = YES;
//    [self.originImageView addSubview:self.sameStickerView];
    self.sameStickerView = [[ZTStickerView alloc] initWithBgView:self.originImageView StickerID:self.newStickerID Img:[view getChangedImage]];
    self.sameStickerView.center = view.center;
    self.sameStickerView.alpha = 0.05;
    self.sameStickerView.delegate = self;
    self.sameStickerView.isOnEdit = YES;
    
    self.backImageTAG = view.tag;
    
    [view.superview addSubview:self.sameStickerView];
    [self tapGesture:view.stickerID clickType:clickType];
    
}
- (void)getSameStickerViewFrame
{
    ZTStickerView * stickerView = [self.view viewWithTag:self.backImageTAG];
    if (self.sameStickerView) {
        stickerView.frame = self.sameStickerView.frame;
    }
}

//colorView代理方法  改变图层颜色
- (void)getColorString:(NSString *)colorString
{
    [self addBeiJingSticker:self.colorView.stickerViewID currentColor:[UIColor hexStringToColor:colorString]];

}
//colorView代理方法   改变图层透明度
- (void)getAlphaValue:(NSInteger)stickerViewID alpha:(float)alpha
{
    [self setStickerAlpha:stickerViewID currentAlpha:alpha];
}
//colorView代理方法  删除图层
- (void)deletCurrentView:(NSInteger)stickerViewID
{
    [self removeSticker:stickerViewID];
    [self.tapView removeFromSuperview];
//    self.tapView.hidden = YES;
    self.colorView.hidden = YES;
}

//改变背景透明度
- (void)setStickerAlpha:(NSInteger)stickerID currentAlpha:(float)currentAlpha
{
    ZTStickerView *stickerView = [self.view viewWithTag:9000 + stickerID];
    stickerView.alpha = currentAlpha;
}

-(NSInteger)newStickerID
{
    _newStickerID++ ;
    
    return _newStickerID ;
}

#pragma mark - 添加贴纸
-(void)addSticker:(UIImage*)image type:(int)type{
    
    ZTStickerView *stickerView = [[ZTStickerView alloc] initWithBgView:self.originImageView StickerID:self.newStickerID Img:image] ;
    self.currentStickerView = stickerView;
    stickerView.delegate = self ;
    stickerView.type = type;
    [_stickerArray addObject:stickerView] ;
    [self makeStickerBecomeFirstRespond:stickerView.stickerID type:type];//1代表图片贴纸
    [_hTable reloadData];
}

#pragma mark - ZTStickerViewDelegate
- (void)makeStickerBecomeFirstRespond:(NSInteger)stickerID type:(int)type;
{
    ZTStickerView *firstSticker;
    
    for (int i=0; i<_stickerArray.count; i++) {
        ZTStickerView *stickerView = _stickerArray[i];
        stickerView.isOnFirst = NO;
        stickerView.isOnEdit = NO;
        if (stickerView.stickerID == stickerID)
        {
            self.currentStickerView = stickerView;
            stickerView.isOnFirst = YES;
            if (type == 1 || type == 4 || type == 5 || type == 6 || type == 7 || type == 8 || type == 9) {//图片贴纸   可编辑
                stickerView.isOnEdit = YES;
            }else if (type == 2){//背景贴纸
                stickerView.isOnEdit = NO;
            }
            [self.originImageView bringSubviewToFront:stickerView];
            firstSticker = stickerView;
        }
    }
    [_stickerArray removeObject:firstSticker];
    [_stickerArray addObject:firstSticker];
}

- (void)removeSticker:(NSInteger)stickerID
{
    for (int i = 0; i < _stickerArray.count; i ++) {
        ZTStickerView *stickerView = _stickerArray[i];
        if (stickerView.stickerID == stickerID) {
            [_stickerArray removeObject:stickerView];
            [stickerView removeFromSuperview];
            self.colorView.hidden = YES;
            [self.colorView removeFromSuperview];
            [self.tapView removeFromSuperview];
            [self.imageEditView removeFromSuperview];
            [self.sameStickerView removeFromSuperview];
            break;
        }
//        if (i != 0) {
//            self.currentStickerView = _stickerArray[i - 1];
//            [self tapGesture:self.currentStickerView.stickerID clickType:0];
//        }else
//        {
//            if (_stickerArray.count > 0) {
//                self.currentStickerView = _stickerArray[0];
//            }
//        }
        
    }
    
    for (ZTStickerView * stickerView in self.stickerArray) {
        self.currentStickerView = stickerView;
    }
    if (self.currentStickerView.type == 1) {//图片
        
        [self tapGesture:self.currentStickerView.stickerID clickType:0];
    }else if (self.currentStickerView.type == 2){//背景
        [self tapGesture:self.currentStickerView.stickerID clickType:1];
        
    }
    

    [_hTable reloadData];
}
//点击贴纸的方法
- (void)tapGesture:(NSInteger)stickerID clickType:(int)clickType
{
    for (int i=0; i<_stickerArray.count; i++) {
        ZTStickerView *stickerView = _stickerArray[i];
        stickerView.isOnEdit = NO;
        if (stickerView.stickerID == stickerID)
        {
            //点击贴纸的方式   tableview和直接点击  默认0 直接点击
            if (clickType == 0) {//直接点击
                
                [self.sameStickerView removeFromSuperview];
                if (stickerView.type == 1 || stickerView.type == 8 || stickerView.type == 9) {//图片 边框  彩色贴纸
                    [self setimageEditView:stickerView imageEditViewType:1];
                }else if (stickerView.type == 4 || stickerView.type == 5 || stickerView.type == 6 || stickerView.type == 7){//形状 贴纸 线条 纹路
                    [self setimageEditView:stickerView imageEditViewType:2];
                }else if (stickerView.type == 10){//文字
                    [self setimageEditView:stickerView imageEditViewType:3];
                }
                
            }else if (clickType == 1){//点tableView的图片
                
                if (stickerView.type == 1 || stickerView.type == 8 || stickerView.type == 9) {//图片
                    [self setimageEditView:stickerView imageEditViewType:1];
                }else if (stickerView.type == 4 || stickerView.type == 5 || stickerView.type == 6 || stickerView.type == 7){//形状
                    [self setimageEditView:stickerView imageEditViewType:2];
                }else if (stickerView.type == 10){//文字
                    [self setimageEditView:stickerView imageEditViewType:3];
                }
                
            }
            self.currentStickerView = stickerView;
            if (stickerView.type == 1 || stickerView.type == 8 || stickerView.type == 9) {
                stickerView.isOnEdit = YES ;
                self.colorView.hidden = YES;
            }else if (stickerView.type == 2){
                stickerView.isOnEdit = NO ;
                [self setColorview:stickerView.alpha];
                self.currentStickerView = stickerView;
                self.colorView.stickerViewID = stickerView.stickerID;
                self.imageEditView.hidden = YES;
            }else if (stickerView.type == 4 || stickerView.type == 5 || stickerView.type == 6 || stickerView.type == 7){//形状
                stickerView.isOnEdit = YES;
            }else if (stickerView.type == 10){//文字
                stickerView.isOnEdit = YES;
            }
        }else
        {
            stickerView.isOnEdit = NO;
        }
    }
    [_hTable reloadData];

}
//move时   改变其他的贴纸的透明度
- (void)alphaChanged:(NSInteger)stickerID
{
    for (int i=0; i<_stickerArray.count; i++) {
        ZTStickerView *stickerView = _stickerArray[i];
        stickerView.alpha = 0.3;
        if (stickerView.stickerID == stickerID)
        {
            stickerView.alpha = 1.0 ;
        }
    }
}
//停止move后   恢复所有贴纸的透明度
- (void)renewAlpha:(NSInteger)stickerID
{
    for (int i=0; i<_stickerArray.count; i++) {
        ZTStickerView *stickerView = _stickerArray[i];
        if (stickerView.type == 1 || stickerView.type == 4 || stickerView.type == 10 || stickerView.type == 5 || stickerView.type == 6 || stickerView.type == 7 || stickerView.type == 8 || stickerView.type == 9) {//图片view
            if (self.imageEditView) {
                stickerView.alpha = self.imageEditView.alphaValue.value;
            }else
            {
                stickerView.alpha = 1.0;
            }
        }else if (stickerView.type == 2) {//背景颜色view
            if (self.colorView) {
                stickerView.alpha = self.colorView.slider.value;
            }else
            {
                stickerView.alpha = 1.0;
            }
        }
    }
}
//停止旋转后 角度
- (void)getAngle:(float)angle
{
    float jiaodu = 180/M_PI * angle;
    NSLog(@"%.2f",jiaodu);
}

#pragma mark - 合成图片
- (UIImage *)pasteStickers:(UIImage*)originImage 
{
    UIGraphicsBeginImageContextWithOptions(originImage.size, NO, 0);
    [originImage drawInRect:CGRectMake(0, 0, originImage.size.width, originImage.size.height)];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    for (ZTStickerView *stickerView in _stickerArray) {
        
        CGRect rect=[stickerView convertRect:stickerView.imgContentView.frame toView:self.originImageView];
        
        CGSize originalSize = originImage.size;
        CGSize newSize = self.originImageView.frame.size;
        CGFloat ratio =originalSize.width/newSize.width;//图片的显示尺寸和绘制到图形上下文中的实际尺寸的比例
        
        rect.origin.x =rect.origin.x*ratio;
        rect.origin.y =rect.origin.y*ratio;
        rect.size.width = rect.size.width*ratio;
        rect.size.height = rect.size.height*ratio;
        
        
        CGContextSaveGState(context);
        
        CGContextTranslateCTM(context, rect.origin.x, rect.origin.y);
        CGContextTranslateCTM(context, 0, rect.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
        
        
        CGContextSetBlendMode (context, kCGBlendModeSourceAtop);
        
        
        //        CGContextDrawImage (context, rect, nil);
        CGContextSetAlpha(context, stickerView.alpha);
        CGContextDrawImage(context, rect, [stickerView getChangedImage].CGImage);
        
        //        [[stickerView getChangedImage] drawInRect:rect];
        
        CGContextRestoreGState(context);
        
    }
    
//    UIGraphicsBeginImageContextWithOptions(self.windowImageView.image.size, NO, 0);
    
    CGContextSetBlendMode (context, kCGBlendModeSourceAtop);
    [self.windowImageView.image drawInRect:CGRectMake(0, 0, self.windowImageView.image.size.width, self.windowImageView.image.size.height)];

    
    //        CGContextDrawImage (context, rect, nil);
    
    
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext() ;
    
    return image;
}

-(void)pasterDone{
    
    FinishViewController *finishVC = [[FinishViewController alloc]init];
    finishVC.finishImage = [self pasteStickers:self.originImageView.image];
    
    [self presentViewController:finishVC animated:YES completion:^{
        
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
